<template>
  <page-header-wrapper>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <a-form layout="inline">
          <a-row :gutter="48">
            <a-col :md="8" :sm="24">
              <a-form-item label="商户">
                <a-input v-model="queryParam.merchantKeyword" placeholder="" />
              </a-form-item>
            </a-col>
            <a-col :md="8" :sm="24">
              <a-form-item label="客户经理">
                <a-input v-model="queryParam.custMagerKeyword" placeholder="" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="8" :sm="24">
                <a-form-item label="还款方案">
                  <a-select v-model="queryParam.repaymentPlanId" placeholder="请选择">
                    <a-select-option
                      :value="item.repaymentPlanId"
                      v-for="item in repaymentPlanSelList"
                      :key="item.repaymentPlanId"
                    >{{ item.repaymentPlanName }}</a-select-option
                    >
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="信用等级">
                  <a-select v-model="queryParam.creditLevel" placeholder="请选择">
                    <a-select-option value="A级">A级</a-select-option>
                    <a-select-option value="B级">B级</a-select-option>
                    <a-select-option value="C级">C级</a-select-option>
                    <a-select-option value="D级">D级</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="状态">
                  <a-select v-model="queryParam.status" placeholder="请选择">
                    <a-select-option value="1">正常</a-select-option>
                    <a-select-option value="2">冻结</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
            </template>

            <a-col :md="8" :sm="24">
              <span
                class="table-page-search-submitButtons"
                :style="(advanced && { float: 'right', overflow: 'hidden' }) || {}"
              >
                <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => (this.queryParam = {})">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'" />
                </a>
              </span>
            </a-col>
          </a-row>
        </a-form>
      </div>

      <s-table
        ref="table"
        size="default"
        rowKey="merchantId"
        :columns="columns"
        :data="loadData"
        :alert="false"
        showPagination="auto"
        listName="dataList"
        :scroll="{ x: 'calc(1500px + 100%)' }"
        v-if="btnsPurviewData.query.isShow"
      >
        <span slot="serial" slot-scope="text, record, index">
          {{ index + 1 }}
        </span>
        <div slot="merchantInfo" slot-scope="text, record">
          <div>{{ record.merchantName }}</div>
          <div>
            <span>{{ record.contactName }}</span
            >&nbsp;&nbsp;<span>{{ record.contactMobile }}</span>
          </div>
        </div>
        <div slot="custUserInfo" slot-scope="text, record">
          <div>{{ record.custUserName }}</div>
          <div>{{ record.custUserMobile }}</div>
        </div>
        <span slot="status" slot-scope="text">
          <a-badge :status="text | statusTypeFilter" :text="text | statusFilter" />
        </span>
        <span slot="action" slot-scope="text, record">
          <template>
            <span v-if="btnsPurviewData.update.isShow">
              <a @click="handleEdit(record)">修改</a>
              <a-divider type="vertical" />
            </span>
            <span v-if="btnsPurviewData.editStatus.isShow">
              <a @click="handleChangeStatus(record)">{{ record.status == 1 ? '冻结' : '启用' }}</a>
              <a-divider type="vertical" />
            </span>
            <a @click="_toDtl(record)" v-if="btnsPurviewData.detail.isShow">查看详情</a>
          </template>
        </span>
      </s-table>
      <create-freeze-form
        ref="createFreezeForm"
        :visible="freezeVisible"
        :loading="confirmLoading"
        :model="mdl"
        @cancel="_cancelFreezeMerchant"
        @ok="_freezeMerchant"
      >
      </create-freeze-form>
      <create-form
        ref="createForm"
        :visible="visible"
        :loading="confirmLoading"
        :title="formTitle"
        :model="mdl"
        @cancel="handleCancel"
        @ok="handleOk"
      >
      </create-form>
    </a-card>
  </page-header-wrapper>
</template>

<script>
import { RouteView } from '@/layouts'
import { BTNS_PURVIEW_MAP } from '@/store/mutation-types'
import storage from 'store'
import { STable, Ellipsis } from '@/components'
import { getMerchantList, editMerchantStatus, updateMerchant } from '@/api/merchantManage'
import { getRepaymentPlanSelList } from '@/api/common'
import CreateFreezeForm from '../modules/CreateFreezeForm'
import CreateForm from '../modules/CreateMerchantForm'
const columns = [
  {
    title: '序号',
    scopedSlots: { customRender: 'serial' },
    align: 'center',
    fixed: 'left',
    width: 80
  },
  {
    title: '商户信息',
    scopedSlots: { customRender: 'merchantInfo' },
    align: 'center'
  },
  {
    title: '信用',
    dataIndex: 'creditLevel',
    align: 'center'
  },
  {
    title: '客户经理',
    scopedSlots: { customRender: 'custUserInfo' },
    align: 'center'
  },
  {
    title: '账单待还/逾期/冻结/总额',
    align: 'center',
    customRender: (record) => {
      return `${record.contractRepaymentAmount}/${record.contractOverdueAmount}/${record.contractAmount}`
    }
  },
  {
    title: '配资待还/待分账/总额',
    align: 'center',
    customRender: (record) => {
      return `${record.capitalRepaymentAmount}/${record.capitalWaitAllocateAmount}/${record.contractFreezeAmount}`
    }
  },
  {
    title: '签约合同数',
    dataIndex: 'contractNums',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '配资数',
    dataIndex: 'capitalNums',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '提前还款方案',
    dataIndex: 'repaymentPlanName',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '商户状态',
    dataIndex: 'status',
    scopedSlots: { customRender: 'status' },
    align: 'center'
  },
  {
    title: '冻结原因',
    dataIndex: 'freezingReason',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    customRender: (text) => text || '—',
    align: 'center'
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '180px',
    scopedSlots: { customRender: 'action' },
    align: 'center',
    fixed: 'right'
  }
]

const statusMap = {
  1: {
    status: 'processing',
    text: '启用'
  },
  2: {
    status: 'default',
    text: '冻结'
  }
}

export default {
  name: 'MerchantList',
  components: {
    STable,
    Ellipsis,
    CreateFreezeForm,
    CreateForm,
    RouteView
  },
  data () {
    this.columns = columns
    return {
      btnsPurviewMap: storage.get(BTNS_PURVIEW_MAP),
      btnsPurviewData: {},
      // create model
      visible: false,
      freezeVisible: false,
      confirmLoading: false,
      mdl: null,
      formTitle: '',
      // 高级搜索 展开/关闭
      advanced: false,
      // 查询参数
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: (parameter) => {
        const requestParameters = Object.assign({}, parameter, this.queryParam)
        return getMerchantList(requestParameters)
          .then((res) => {
            return res.result
          })
          .catch((e) => {})
      },
      selectedRowKeys: [],
      selectedRows: [],
      repaymentPlanSelList: []
    }
  },
  filters: {
    statusFilter (type) {
      return statusMap[type].text
    },
    statusTypeFilter (type) {
      return statusMap[type].status
    }
  },
  created () {
    getRepaymentPlanSelList({})
      .then((res) => {
        this.repaymentPlanSelList = res.dataList
      })
      .catch((e) => {})
    this.btnsPurviewData = this.btnsPurviewMap[this.$route.meta.permission[0]]
  },
  computed: {},
  methods: {
    /**
     * 取消冻结商户
     */
    _cancelFreezeMerchant () {
      this.freezeVisible = false
    },
    /**
     * 冻结商户
     */
    _freezeMerchant () {
      const form = this.$refs.createFreezeForm.freezeForm
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        if (!errors) {
          editMerchantStatus({
            freezingReason: values.freezingReason,
            status: 2,
            merchantList: [{ merchantId: values.id }]
          })
            .then((res) => {
              this.freezeVisible = false
              this.confirmLoading = false
              this.$refs.table.refresh()
              this.$message.info(`冻结成功`)
            })
            .catch((e) => {
              this.confirmLoading = false
            })
        } else {
          this.confirmLoading = false
        }
      })
    },
    /**
     * 查看详情
     */
    _toDtl (record) {
      this.$router.push({ path: `/merchantManage/MerchantDtl/${record.merchantId}` })
    },
    /**
     * 切换searchBar展开/关闭
     */
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    /**
     * 修改角色
     */
    handleEdit (record) {
      const form = this.$refs.createForm.form
      form.resetFields() // 清理表单数据（可不做）
      this.visible = true
      this.formTitle = '修改商户'
      this.mdl = { ...record }
    },
    /**
     * 切换商户状态
     */
    handleChangeStatus (record) {
      const params = { status: record.status === 1 ? 2 : 1, merchantList: [{ merchantId: record.merchantId }] }
      if (record.status === 2) {
        editMerchantStatus(params)
          .then((res) => {
            this.$refs.table.refresh()
            this.$message.info(`${record.status === 1 ? '冻结' : '启用'}成功`)
          })
          .catch((e) => {})
      } else {
        const form = this.$refs.createFreezeForm.freezeForm
        form.resetFields() // 清理表单数据（可不做）
        this.freezeVisible = true
        this.mdl = { id: record.merchantId, freezingReason: '' }
      }
    },
    /**
     *  新建/修改商户
     */
    handleOk () {
      const form = this.$refs.createForm.form
      this.confirmLoading = true
      form.validateFields((errors, values) => {
        console.log(values)
        if (!errors) {
          if (values.merchantId) {
            // 修改 e.g.
            updateMerchant(values)
              .then((res) => {
                this.visible = false
                this.confirmLoading = false
                // 刷新表格
                this.$refs.table.refresh()
                this.$message.info('修改成功')
              })
              .catch((e) => {
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    /**
     * 取消表单
     */
    handleCancel () {
      this.visible = false
      this.confirmLoading = false
    }
  }
}
</script>
